<script setup lang="ts">
import Scrollbar from "smooth-scrollbar";
import { onMounted, onUnmounted, shallowRef } from "vue";
import type { ScrollbarOptions, ScrollStatus } from "smooth-scrollbar/interfaces";
import "./scroll-view-plugins.ts";
import type { ScrollViewRef } from "@/components/framework/scroll-view-types.ts";

const { options } = defineProps<{
  options?: Partial<ScrollbarOptions>;
}>();

const emits = defineEmits<{
  (e: "scroll", scrollbar: Scrollbar, status: ScrollStatus): void;
}>();

const container = shallowRef<HTMLDivElement>();
const scrollbarRef = shallowRef<Scrollbar>();

const onScroll = (status: ScrollStatus) => {
  emits("scroll", scrollbarRef.value!, status);
};

onMounted(() => {
  const el = container.value!;
  const scrollbar = Scrollbar.init(el, { alwaysShowTracks: false, ...options });
  scrollbar.updatePluginOptions("overscroll", { effect: "glow" });
  scrollbarRef.value = scrollbar;
  scrollbar.addListener(onScroll);
});

onUnmounted(() => {
  if (scrollbarRef.value) {
    scrollbarRef.value.removeListener(onScroll);
    scrollbarRef.value.destroy();
  }
});

defineExpose<ScrollViewRef>({
  scrollbar: () => scrollbarRef.value!,
  scrollTo: (x, y, duration, opts) => scrollbarRef.value?.scrollTo(x, y, duration, opts),
});
</script>

<template>
  <div class="scroll-view" ref="container">
    <slot />
  </div>
</template>

<style lang="less">
.scroll-view {
  width: 100%;
  height: 100%;
  overflow: auto;

  .scrollbar-track {
    border-radius: 4px;
  }
}
</style>
